<!-- eslint-disable vue/valid-v-for -->
<template>
  <div class="emp-comp-table">
    <div class="header" v-if="searchData.length">
      <el-form
        :inline="true"
        class="search-form"
        :model="searchObj"
        ref="ruleFormRef"
      >
        <template v-for="(item, index) in searchData" :key="index">
          <el-form-item
            :label="item.label"
            v-show="isExpand ? isExpand : index < 4"
          >
            <template v-if="item.valueType === 'input'">
              <el-input
                v-model="searchObj[item.name]"
                :placeholder="`请输入${item.label}`"
                clearable
                @change="handleSearch"
              />
            </template>
            <template v-if="item.valueType === 'select'">
              <el-select
                style="width: 200px"
                v-model="searchObj[item.name]"
                :placeholder="`请选择${item.label}`"
                clearable
                @change="handleSearch"
              >
                <el-option
                  v-for="ite in item.options"
                  :key="ite.code"
                  :label="ite.name"
                  :value="ite.code"
                />
              </el-select>
            </template>
            <template v-if="item.valueType === 'date' && item.isPicker">
              <el-date-picker
                v-model="searchObj[item.name]"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                type="date"
                :placeholder="`选择${item.label}`"
                @change="handleSearch"
              />
            </template>
          </el-form-item>
        </template>
      </el-form>
      <div class="search">
        <el-button type="primary" @click="handleSearch" :icon="Search">
          查询
        </el-button>
        <el-button @click="handleReset(ruleFormRef)">重置</el-button>
        <el-button link type="primary" @click="isExpand = !isExpand">
          {{ isExpand ? "合并" : "展开" }}
          <el-icon>
            <arrow-down v-if="!isExpand" />
            <arrow-up v-else />
          </el-icon>
        </el-button>
      </div>
    </div>
    <div class="footer">
      <div class="operator">
        <slot name="btn"></slot>
      </div>
      <div class="table">
        <el-table
          class="emp-table"
          v-loading="loading"
          @selection-change="(val) => emit('selection-change', val)"
          :data="list"
          row-key="id"
          :border="true"
        >
          <template v-for="item in columns">
            <el-table-column
              v-if="item.type === 'index'"
              :type="item.type"
              :width="item.width"
              :min-width="item.minWidth"
              :align="item.align != null ? item.align : 'center'"
              :fixed="item.fixed"
              :label="item.label"
            >
              <template #default="scope">
                <span>
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="item.type === 'image'"
              :type="item.type"
              :width="item.width"
              :min-width="item.minWidth"
              :align="item.align != null ? item.align : 'center'"
              :fixed="item.fixed"
              :label="item.label"
            >
              <template #default="scope">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row[item.name]"
                  fit="fill"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="item.type"
              :type="item.type"
              :width="item.width"
              :min-width="item.minWidth"
              :align="item.align != null ? item.align : 'center'"
              :fixed="item.fixed"
              :label="item.label"
            />
            <el-table-column
              v-else
              :prop="item.name"
              :width="item.width"
              :min-width="item.minWidth"
              :align="item.align != null ? item.align : 'center'"
              :fixed="item.fixed"
              :label="item.label"
            >
              <template #default="scope">
                <span v-if="!item.slot && item.valueType === 'date'">
                  {{ FormatDate(scope.row[item.name]) }}
                </span>
                <span v-else-if="!item.slot && item.valueType === 'datetime'">
                  {{ FormatDateTime(scope.row[item.name]) }}
                </span>
                <span v-else-if="!item.slot && item.valueType === 'time'">
                  {{ FormatTime(scope.row[item.name]) }}
                </span>
                <span v-else-if="!item.slot">{{ scope.row[item.name] }}</span>
                <slot
                  v-else
                  :name="item.name"
                  :item="item"
                  :row="scope.row"
                ></slot>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <!-- ------------分页--------------->
      <div class="pagination">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { watch, ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";

import { FormatDate, FormatDateTime, FormatTime } from "@/utils/formatters";
import { onMounted } from "vue";

const ruleFormRef = ref<FormInstance>();
const emit = defineEmits([
  "onReset",
  "onSearch",
  "onDelete",
  "selection-change",
]);
let props = defineProps({
  columns: {
    // type: Array<{
    //   name: string
    //   label: string
    //   inSearch: boolean
    //   type: string
    //   slot: boolean
    //   align: string
    //   width: number
    //   minWidth: number
    //   fixed: boolean
    //   valueType: string
    //   options: Array<{ id: string; name: string; code: string }>
    // }>,
    type: Array<any>,
    default: () => [],
  },
  list: {
    type: Array,
    default: () => [],
  },
  total: {
    type: Number,
    default: 0,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const searchData = ref([]);

const searchObj = ref({});

watch(
  () => props.columns,
  (newColumns) => {
    updateColumns();
  }
);

const updateColumns = () => {
  let obj = {};
  let search = [];
  for (let item of props.columns) {
    if (item.inSearch) {
      obj[item.name] = null;
    }
    if (item.inSearch) {
      search.push(item);
    }
  }
  searchData.value = search;
  searchObj.value = obj;
};

// 当前页
const currentPage = ref(1);
// 页大小
const pageSize = ref(parseInt(import.meta.env.VITE_APP_PAGE_SIZE));
// 收缩展开
const isExpand = ref(false);

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  handleSearch();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  handleSearch();
};

const handleSearch = () => {
  const obj = Object.assign({}, searchObj.value, {
    skipCount: (currentPage.value - 1) * pageSize.value,
    maxResultCount: pageSize.value,
  });
  emit("onSearch", obj);
};

const handleReset = (formEl: FormInstance | undefined) => {
  searchData.value.forEach((item) => {
    searchObj.value[item.name] = null;
  });

  const obj = Object.assign({}, searchObj.value, {
    skipCount: (currentPage.value - 1) * pageSize.value,
    maxResultCount: pageSize.value,
  });
  emit("onReset", obj);
};

onMounted(() => {
  updateColumns();
});

defineExpose({ handleSearch });
</script>
<style scoped lang="scss">
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.emp-comp-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    padding: 16px 16px 0 16px;
    margin-bottom: 12px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
    // border-top: 3px solid #50a6ff;
    .search-form {
      flex: 1;
      :deep(.ep-input--default) {
        width: 200px;
      }
    }
    .search {
      flex-shrink: 0;
      white-space: nowrap;
    }
  }
  .footer {
    flex: 1;
    display: flex;
    padding: 16px;
    flex-direction: column;
    border-radius: 4px;
    overflow: hidden;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
    min-height: 300px;
    .operator {
      margin-bottom: 15px;
    }
    .table {
      position: relative;
      flex: 1;
    }
    .emp-table {
      position: absolute;
      height: 100%;
    }
  }
  :deep(.ep-table__header th) {
    font-size: 15px;
    font-weight: 700;
    color: #252525;
  }

  .pagination {
    width: 100%;
    display: flex;
    justify-content: center;
    padding-top: 20px;
    box-sizing: border-box;
  }
}
</style>
